package edu.towson.cis.cosc490.jpanne.npr.main;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import edu.towson.cis.cosc490.jpanne.npr.R;
import edu.towson.cis.cosc490.jpanne.npr.data.Constants;
import edu.towson.cis.cosc490.jpanne.npr.data.NPRData;

public class SavedArticles extends ListActivity {
	private NPRData savedArticleData;
	private Cursor cursor;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		savedArticleData = new NPRData(this);
		setContentView(R.layout.activity_saved_articles);
		updateDisplay();
	}
	
	protected void onResume(){
		super.onResume();
		updateDisplay();
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		cursor.moveToPosition(position);
		String link = cursor.getString(cursor.getColumnIndex(Constants.LINK));
		Intent viewMessage = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
		startActivity(viewMessage);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.saved_articles, menu);
		return true;
	}
	
	private void updateDisplay(){
		cursor = getSavedArticlesCursor();
		String[] FROM = {Constants.TITLE, Constants.LINK};
    	int[] TO = {R.id.TextView01};
    	SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.npr_item, cursor, FROM, TO);
		setListAdapter(sca);
	}
	
	private Cursor getSavedArticlesCursor(){
		SQLiteDatabase db = savedArticleData.getReadableDatabase();
		Cursor cursor = db.query(Constants.TABLE_NAME, null, "saved=?" , new String[]{"1"}, null, null, "_ID ASC");
		startManagingCursor(cursor);
		return cursor;
	}
	
	protected void onStop(){
		super.onStop();
		stopManagingCursor(cursor);
	}

}
